import { Button, Dialog, LoadingPlugin, MessagePlugin, Upload } from 'tdesign-vue-next';
import { defineComponent, h, ref, toRefs } from 'vue';

import { useUserStore } from '@/store';

export default defineComponent({
  name: 'ImportExcelComponent',
  props: {
    uploadProps: {
      type: Object,
      default: () => {
        return {};
      },
    },
    buttonProps: {
      type: Object,
      default: () => {
        return {};
      },
    },
  },
  emits: ['fetchData', 'oneFileSuccess', 'error'],
  setup(props, { emit, slots }) {
    const { uploadProps, buttonProps } = toRefs(props);

    const errorInfo = ref([]);
    const errorDialogVisible = ref(false);
    // 上传后回调
    const onOneFileSuccess = (params: any) => {
      if (params.response.status === '200') {
        emit('oneFileSuccess', params);
        MessagePlugin.success('导入成功');
        emit('fetchData');
      } else if (params.response.data) {
        errorInfo.value = params.response.data;
        errorDialogVisible.value = true;
        emit('error', params.response.data);
      } else {
        MessagePlugin.error(params.response.message);
      }
      LoadingPlugin(false);
    };

    // 上传前回调
    const onSelectChange = () => {
      LoadingPlugin(true);
    };

    const onFail = (params: any) => {
      console.error(params);
      MessagePlugin.error('上传失败');
      LoadingPlugin(false);
    };

    const files = ref([]);

    const { token } = useUserStore();

    return () => (
      <div>
        {h(
          Upload,
          {
            theme: 'custom',
            modelValue: files.value,
            'onUpdate:modelValue': (checked: any) => {
              files.value = checked;
            },
            accept: '.xls,.xlsx',
            multiple: true,
            triggerButtonProps: { theme: 'primary', variant: 'base', default: '导入' },
            headers: { Authorization: token },
            onOneFileSuccess,
            onSelectChange,
            onFail,
            allowUploadDuplicateFile: true,
            ...uploadProps.value,
          },
          () => h(Button, { theme: 'primary', content: '导入', ...buttonProps.value }),
        )}

        <Dialog
          v-model:visible={errorDialogVisible.value}
          attach="body"
          footer={false}
          closeOnOverlayClick={false}
          zIndex={5501}
        >
          {slots.error?.({ errorInfo: errorInfo.value })}
        </Dialog>
      </div>
    );
  },
});
